//
//  CXPayManager.m

//

#import "CXPayManager.h"
#import <AlipaySDK/AlipaySDK.h>


#import "APOrderInfo.h"
#import "APRSASigner.h"

#import "CXAlertView.h"
#import "WXApi.h"
static CXPayManager *_instance = nil;
@interface CXPayManager()

@end
@implementation CXPayManager

+(instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
        //注册登录状态监听
        [[NSNotificationCenter defaultCenter] addObserver:_instance selector:@selector(doPayPush:) name:HNTPayPushNotification object:nil];
    });
    return _instance;
}

+(instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

+(id)copyWithZone:(nullable NSZone *)zone{
    return _instance;
}

#pragma mark ———— 调起支付 ————
/**
 调起支付
 
 @param payType 支付方式
 @param params 支付参数
 */
-(void)orderPay:(UsePayType)payType targetController:(id)target params:(NSDictionary *)params completedCallBack:(PayCompletedCallBack)completedCallBack
{
    self.payCompletedCallBack = completedCallBack;
    if (payType == kUsePayTypeAliPay) {
        [self doAliPay:params];
    }else if (payType == kUsePayTypeWeChatPay) {
        [self doWXPay:params];
    }else{
        [CXAlertView showWithTitle:@"确认支付吗？" message:@"金额会直接从您的余额中扣除，确认要继续支付吗？" cancelButtonTitle:@"取消" otherButtonTitle:@"继续支付" clickButtonBlock:^(CXAlertView * _Nonnull alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                // 确认
                [self doBalancePay:params];
            }
        }];
        
    }
}

/**
 支付宝支付
 
 @param dict 订单编号等订单信息
 */
-(void)doAliPay:(NSDictionary *)dict
{
    NSString *orderString = dict[@"url"];
    NSString *appScheme = HNTAliPayScheme;
    
    if (orderString != nil)
    {
        // NOTE: 调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
           
            if ([resultDic[@"resultStatus"] intValue] == 9000)
            {
                [MBManager showBriefAlert:@"支付成功" inView:nil];
            }else if ([resultDic[@"resultStatus"] intValue] == 6001)
            {
                [MBManager showBriefAlert:@"用户中途取消" inView:nil];
            }else if ([resultDic[@"resultStatus"] intValue] == 6002)
            {
                [MBManager showBriefAlert:@"网络连接出错" inView:nil];
            }else if ([resultDic[@"resultStatus"] intValue] == 4000)
            {
                [MBManager showBriefAlert:@"订单支付失败" inView:nil];
                HXLog(@"失败原因%@",resultDic);
            }
        }];
    }
    else
    {
        [MBManager showBriefAlert:@"支付参数错误，请选择其他支付方式" inView:nil];
    }
}

// 微信支付
-(void)doWXPay:(NSDictionary *)dict
{
//     NSLog(@"dict---%@",dict);
    NSDictionary *paraDic = dict[@"url"];
    if([WXApi isWXAppInstalled]) // 判断 用户是否安装微信
    {
//        NSLog(@"paraDic---%@",paraDic[@"appid"]);
        //需要创建这个支付对象
        PayReq *req   = [[PayReq alloc] init];
        //由用户微信号和AppID组成的唯一标识，用于校验微信用户
        req.openID = paraDic[@"appid"];
        
        // 商家id，在注册的时候给的
        req.partnerId = paraDic[@"partnerid"];
        
        // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
        req.prepayId  = paraDic[@"prepayid"];
        
        // 根据财付通文档填写的数据和签名
        //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
        req.package   = paraDic[@"packagex"];
        
        // 随机编码，为了防止重复的，在后台生成
        req.nonceStr  = paraDic[@"noncestr"];
        
        // 这个是时间戳，也是在后台生成的，为了验证支付的
        NSString * stamp = paraDic[@"timestamp"];
        req.timeStamp = stamp.intValue;
        
        // 这个签名也是后台做的
        req.sign = paraDic[@"sign"];
        
//        NSLog(@"req---%@",req);
        
        
        [WXApi startLogByLevel:WXLogLevelDetail logBlock:^(NSString * _Nonnull log) {
                  NSLog(@"%@",log);
              }];
        //发送请求到微信，等待微信返回onResp
        [WXApi sendReq:req completion:NULL];
      
        
    }else
    {
        [MBManager showBriefAlert:@"未安装微信" inView:nil];
    }
}

-(void)doBalancePay:(NSDictionary *)dict
{
    /*
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"action"] = @"order_yue_pay";
    parameters[@"uid"] = [MSUserManager sharedInstance].curUserInfo.uid;//用户id
    parameters[@"token"] = [MSUserManager sharedInstance].curUserInfo.token;//用户token,注册或登录时返回的值
    parameters[@"oid"] = dict[@"oid"];//订单oid
    parameters[@"order_no"] = dict[@"order_no"];//订单号
    NSDictionary *paraDic = [ZzqFunctionTools parameters:[ZzqFunctionTools dictionaryToJson:parameters]];
    HXWeakSelf(self);
    [[HXNetworkTool shareTool] request:POST urlString:HXRC_MainURL parameters:paraDic finished:^(id responseObject, NSError *error){
        if (error != nil) {
            [MBProgressHUD showTitleToView:nil postion:NHHUDPostionBottom title:error.localizedDescription];
            return;
        }
        if([[responseObject objectForKey:@"status"] integerValue] == 1) {
            [MBProgressHUD showTitleToView:nil postion:NHHUDPostionBottom title:[responseObject objectForKey:@"message"]];
            if (weakself.payCompletedCallBack) {
                weakself.payCompletedCallBack(@{@"result":@"1"});
            }
        } else {
            [MBProgressHUD showTitleToView:nil postion:NHHUDPostionBottom title:[responseObject objectForKey:@"message"]];
            if (weakself.payCompletedCallBack) {
                weakself.payCompletedCallBack(@{@"result":@"0"});
            }
        }
    }];*/
}

#pragma mark -- 处理通知
-(void)doPayPush:(NSNotification *)note
{
//    NSLog(@"处理通知note---%@",note);
    if (self.payCompletedCallBack)
    {
        self.payCompletedCallBack(note.userInfo);
    }
}

#pragma mark -
#pragma mark   ==============产生随机订单号==============

- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}

@end
